﻿(function () {

    layui.use(["layer", "jquery", "table", "form"], function () {
        var layer = layui.layer;
        var $ = layui.jquery;
        var table = layui.table;
        var form = layui.form;

        $(document).ready(function () {
            $("#addAdminBtn").click(onAddAdminBtnClick);
            $("#btnRefresh").click(onRefreshBtnClick);

            table.render({
                elem: "#Table",
                url: "/Admin/List",
                height: "full-61", // (10 + 30 + 10 + 10 + 1)
                page: false,
                method: "POST",
                even: true,
                parseData: function (res) {
                    //console.log(res);
                    return {
                        "code": res.Success == true ? 0 : -1,
                        "msg": res.Msg,
                        "count": res.Count,
                        "data": res.Data
                    };
                },
                cols: [[
                    { field: "Id", hide: true }
                    , { field: "UserName", width: 120, align: "center", title: "用户名" }
                    , { field: "Name", width: 120, align: "center", title: "姓名" }
                    , { field: "CreateTime", width: 220, align: "center", title: "创建时间" }
                    , {
                        field: "ShopName", width: 120, align: "center", title: "关联店铺", templet: function (row) {
                            if (row.ShopName == "" || row.ShopName == null) {
                                return "--";
                            } else {
                                return row.ShopName;
                            }
                        }
                    }
                    , { align: "center", title: "操作", toolbar: "#tableToolBar" }
                ]]
            });

            table.on("tool(admin)", function (obj) {
                var layEvent = obj.event;

                if (layEvent == "reset") {
                    onResetHandler(obj);
                }
                else if (layEvent == "delete") {
                    onDeleteHandler(obj);
                }
            });
        });

        function reloadTable() {
            table.reload("Table");
        }

        function onDeleteHandler(obj) {
            var data = obj.data;

            layer.confirm("确定要删除用户吗？"
                , { icon: 3, title: "满堂创品", offset: "20%" }
                , function () {
                    var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                        {
                            icon: 16, shade: 0.01, offset: ["25%"], time: false
                        });
                    $.ajax("/Admin/Delete", {
                        type: "POST",
                        data: "adminId=" + data.Id,
                        complete: function (jqXHR, textStatus) {
                            layer.close(loadingIndex);
                        },
                        success: function (data, textStatus, jqXHR) {
                            //console.log(data);
                            if (data.Success == true) {
                                layer.msg(addStyle("删除成功！"), {
                                    icon: 1, time: 1 * 1000, offset: ["25%"], end: function () {
                                        reloadTable();
                                    }
                                });
                            } else {
                                layer.msg(addStyle("删除失败: " + data.Msg),
                                    { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                                );
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            layer.msg(addStyle("系统错误，请联系管理员！"),
                                { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                            );
                        }
                    });
                }
            );
        }

        function onResetHandler(obj) {
            var data = obj.data;
            var layEvent = obj.event;
            var tr = obj.tr;
            var _adminId = data.Id;

            var _layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                offset: "10%",
                content: $("#ResetPwdDialog").html()
            });

            $("#txtResetPwd").val("");
            $("#txtResetNewPwd").val("");
            $("#txtResetNewPwd2").val("");

            form.verify({
                pwd: [/\w{6, 15}/, "密码格式不正确！"],
                pwd2: function (value, elem) {
                    if ($("#txtResetNewPwd").val() != $("#txtResetNewPwd2").val()) {
                        return "两次新密码输入不一致！"
                    }
                    return;
                }
            });

            form.on("submit(filter-reset)", function (data) {
                //console.log(data);

                layer.confirm("确定要重设密码吗？",
                    { icon: 3, title: "满堂创品", offset: "20%" },
                    function () {
                        var jsonData = {
                            Pwd: hex_md5($("#txtResetPwd").val()).toUpperCase(),
                            NewPwd: hex_md5($("#txtResetNewPwd").val()).toUpperCase(),
                            ConfirmNewPwd: hex_md5($("#txtResetNewPwd2").val()).toUpperCase(),
                            AdminId: _adminId
                        };
                        //console.log(jsonData);

                        var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                            { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                        $.ajax("/Admin/ResetPwd", {
                            method: "POST",
                            data: jsonData,
                            complete: function (jqXHR, textStatus) {
                                layer.close(loadingIndex);
                            },
                            success: function (data, textStatus, jqXHR) {
                                if (data.Success == true) {
                                    layer.close(_layerId);
                                    layer.msg(addStyle("重设密码成功！"), {
                                        icon: 1, time: 1 * 1000, offset: ["25%"], end: function () {
                                            reloadTable();
                                        }
                                    });
                                } else {
                                    layer.msg(addStyle("重设密码失败: " + data.Msg),
                                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true }
                                    );
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.msg(addStyle("系统错误，请联系管理员！"),
                                    { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                            }
                        });
                    }
                );

                return false;
            });
        }

        function onAddAdminBtnClick() {
            form.verify({
                username: [/\w{5,20}/, "用户名格式不正确！"],
                password: [/\w{6,20}/, "密码格式不正确！"],
                name: [/^[\u4e00-\u9fa5a-zA-Z0-9]{2,10}$/, "姓名格式不正确！"]
            });

            var _layerId = layer.open({
                type: 1,
                title: "满堂创品",
                shade: [0.1, '#000'],
                skin: 'layui-layer-molv',
                offset: "10%",
                content: '<div id="addAdminDialog2">' + $("#addAdminDialog").html() + '</div>'
            });

            var sel = $("#addAdminDialog2 select[name=selAddAdmin]");
            //alert(sel.length);

            var loadingIndex = layer.msg(addStyle("正在加载 ......"),
                { icon: 16, shade: 0.01, offset: ["25%"], time: false });
            $.ajax("/Admin/GetShopList", {
                method: "POST",
                complete: function (jqXHR, textStatus) {
                    layer.close(loadingIndex);
                },
                success: function (data, textStatus, jqXHR) {
                    if (data.Success == true) {
                        for (var i = 0; i < data.Data.length; i++) {
                            var text = data.Data[i].Name;
                            var value = data.Data[i].ShopManagerUserId;
                            var option = new Option(text, value);
                            sel.append(option);
                        }
                        form.render("select");
                    }
                }
            });

            form.on("submit(filter-AddAdminBtn)", function (data) {
                var jsonData = {
                    ShopManagerUserId: $("#addAdminDialog2 select[name=selAddAdmin]").val(),
                    UserName: $("#addAdminDialog2 input[name=txtAddDlg_UserName]").val(),
                    Pwd: hex_md5($("#addAdminDialog2 input[name=txtAddDlg_Pwd]").val()).toUpperCase(),
                    Name: $("#addAdminDialog2 input[name=txtAddDlg_Name]").val()
                };
                //console.log(jsonData);

                layer.confirm("确定要添加新用户吗？",
                    { icon: 3, title: "满堂创品", offset: "20%" },
                    function () {
                        var loadingIndex = layer.msg(addStyle("正在处理 ......"),
                            { icon: 16, shade: 0.01, offset: ["25%"], time: false });
                        $.ajax("/Admin/AddAdmin", {
                            method: "POST",
                            data: jsonData,
                            complete: function (jqXHR, textStatus) {
                                layer.close(loadingIndex);
                            },
                            success: function (data, textStatus, jqXHR) {
                                if (data.Success == true) {
                                    layer.close(_layerId);
                                    layer.msg(addStyle("添加新用户成功！"), {
                                        icon: 1, time: 1 * 1000, offset: ["25%"], end: function () {
                                            reloadTable();
                                        }
                                    });
                                } else {
                                    layer.msg(addStyle("添加新用户失败: " + data.Msg),
                                        { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                                }
                            },
                            error: function (XMLHttpRequest, textStatus, errorThrown) {
                                layer.msg(addStyle("系统错误，请联系管理员！"),
                                    { icon: 2, time: 3 * 1000, offset: ["25%"], closeBtn: true });
                            }
                        });
                    }
                );

                return false;
            });
        }

        function onRefreshBtnClick() {
            reloadTable();
        }

        function addStyle(str) {
            return '<span style="font-size: 16px;">' + str + '</span>';
        }
    });

})();